package com.jielihaofeng.publisher;


import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author Johnnie Wind
 * @description Routing 生产者
 * @date 2021/11/29 17:48
 */
public class Producer_Routing {
    public static void main(String[] args) throws IOException, TimeoutException {

        // 1. 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();

        // 2. 设置连接参数
        connectionFactory.setHost("47.113.86.188");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/wzy");
        connectionFactory.setUsername("wuzhengyu");
        connectionFactory.setPassword("123456");

        // 3. 获取连接
        Connection connection = connectionFactory.newConnection();

        // 4. 创建 Channel
        Channel channel = connection.createChannel();

        /*
         * exchange：交换机名称
         * type：交换机类型
                DIRECT("direct")：定向
                FANOUT("fanout")：扇形（广播），发送消息到每一个与之绑定队列
                TOPIC("topic")：通配符的方式
                HEADERS("headers")：参数匹配
         * durable：是否持久化
         * autoDelete：自动删除
         * internal：内部使用，一般false
         * arguments：参数
         */
        // 5. 创建交换机
        String exchangeName = "test_direct";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true, false, false, null);

        // 6. 创建队列
        String queue1Name = "test_direct_queue1";
        String queue2Name = "test_direct_queue2";

        channel.queueDeclare(queue1Name, true, false, false, null);
        channel.queueDeclare(queue2Name, true, false, false, null);

        // 7. 绑定队列和交换机
        /*
         * queueBind(String queue, String exchange, String routingKey)
         * queue：队列名称
         * exchange：交换机名称
         * routingKey：路由键，绑定规则。如果交换机的类型为fanout，routingKey设置为""
         */
        // 队列1绑定 error
        channel.queueBind(queue1Name, exchangeName, "error");
        // 队列2绑定 info error warning
        channel.queueBind(queue2Name, exchangeName, "info");
        channel.queueBind(queue2Name, exchangeName, "error");
        channel.queueBind(queue2Name, exchangeName, "warning");

        // 8. 发送消息
        String body = "日志信息：张三调用了findAll方法...日志级别：info...";
        channel.basicPublish(exchangeName, "info", null, body.getBytes());

        String body2 = "日志信息：张三调用了delete方法...日志级别：error...";
        channel.basicPublish(exchangeName, "error", null, body2.getBytes());

        // 9. 释放资源
        channel.close();
        connection.close();
    }
}
